﻿using Dapper;
using MySql.Data.MySqlClient;
using System;
using System.Data;
using System.IO;
using System.Text;
using CommServer.Common.Json;

namespace CommServer.Common.Database
{
    public class DbHelper
    {
        private const string DEFAULT_DBCONNECTSTRING = "server=127.0.0.1;database=kd-pv-db;uid=root;pwd=root;charset='utf8';SslMode=None";
        private static JsonValue m_Config;

        static DbHelper()
        {
            if (!File.Exists("config.json"))
            {
                Console.WriteLine("config.json not exist");
                m_Config = new JsonObject();
                return;
            }

            string s = File.ReadAllText("config.json");
            bool b = JsonValue.TryParse(s, out m_Config);
            if (!b)
            {
                Console.WriteLine("config.json cannot parse");
            }
        }
        public static IDbConnection GetConn()
        {
            string strConn = DEFAULT_DBCONNECTSTRING;
            if (m_Config.ContainsKey("DbConnectString"))
            {
                strConn = m_Config["DbConnectString"];
            }
            MySqlConnection conn = new MySqlConnection(strConn);
            conn.Open();
            return conn;
        }

        public static int Execute(StringBuilder Sql)
        {
            using (var conn = GetConn())
            {
                //Log.Info(Sql.ToString());
                return conn.Execute(Sql.ToString());
            }
        }
        public static int Execute(string Sql)
        {
            using (var conn = GetConn())
            {
                Log.Debug(Sql);
                return conn.Execute(Sql);
            }
        }
        public static void CreateTable()
        {
            string Sql = "create table if not exists KD_RtuInfo(" +
                             " RtuSN    VARCHAR(32) NOT NULL ," +
                             " SimSN    VARCHAR(32) NOT NULL DEFAULT ''," +
                             " SimNo    VARCHAR(32) NOT NULL DEFAULT ''," +
                             " SVer     VARCHAR(32) NOT NULL DEFAULT ''," +
                            " PRIMARY KEY(RtuSN)" +
                        ")" +
                        " ENGINE = INNODB " +
                        " DEFAULT CHARSET = utf8;";
            using (var conn = GetConn())
            {
                conn.Execute(Sql);
            }
        }
    }
}
